﻿using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace LvcChong
{
    public class DESHelper
    {
        public const string CONNECTION_STRING_IV = "DFBJHLS.";
        public const string CONNECTION_STRING_KEY = "88888888";

        #region DES加密

        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="sInputString">输入字符</param>
        /// <param name="sKey">Key(8位长度字符串)</param>
        /// <param name="IV">偏移向量(8位长度字符串)</param>
        /// <returns>加密结果</returns>
        public static string DesEncrypt(string str, string key = CONNECTION_STRING_KEY, string IV = CONNECTION_STRING_IV)
        {
            byte[] data = Encoding.UTF8.GetBytes(str);
            byte[] result;
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = Encoding.UTF8.GetBytes(key);
            DES.IV = Encoding.UTF8.GetBytes(IV);
            ICryptoTransform desencrypt = DES.CreateEncryptor();
            result = desencrypt.TransformFinalBlock(data, 0, data.Length);
            return Convert.ToBase64String(result);
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="sInputString">输入字符</param>
        /// <param name="sKey">Key(8位长度字符串)</param>
        /// <param name="IV">偏移向量(8位长度字符串)</param>
        /// <returns>解密结果</returns>
        public static string DesDecrypt(string str, string key = CONNECTION_STRING_KEY, string IV = CONNECTION_STRING_IV)
        {
            try
            {
                if (!IsBase64String(str)) return str;
                byte[] data = Convert.FromBase64String(str);
                DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
                DES.Key = Encoding.UTF8.GetBytes(key);
                DES.IV = Encoding.UTF8.GetBytes(IV);
                ICryptoTransform desencrypt = DES.CreateDecryptor();
                byte[] result = desencrypt.TransformFinalBlock(data, 0, data.Length);
                return Encoding.UTF8.GetString(result);
            }
            catch
            {
                return str;
            }
        }

        public static bool IsBase64String(string s)
        {
            s = s.Trim();
            return (s.Length % 4 == 0) && Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,3}$", RegexOptions.None);
        }

        #endregion DES加密
    }
}